package com.hillky.emos.wx.config.shiro;

import cn.hutool.core.util.ObjectUtil;
import com.hillky.emos.wx.domain.TbUser;
import com.hillky.emos.wx.exception.EmosException;
import com.hillky.emos.wx.service.TbUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.realm.SimpleAccountRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Set;

@Component
public class OAuth2Realm extends AuthorizingRealm {

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private TbUserService userService;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof OAuth2Token;
    }

    /**
     * 授权(验证权限时调用)
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        // 查询用户权限列表
        // 往info对象中添加权限列表
        TbUser user = (TbUser) principalCollection.getPrimaryPrincipal();
        Integer userId = user.getId();
        Set<String> permissions = userService.searchUserPermissions(userId);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setStringPermissions(permissions);
        return info;
    }


    /**
     * 认证(登陆时调用)
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        // 从令牌中获取userId,然后检测账户是否被冻结
        String token = (String) authenticationToken.getPrincipal();
        int userId = jwtUtil.getUserId(token);
        TbUser user = userService.searchById(userId);
        if(ObjectUtil.isNull(user)){
            throw new LockedAccountException("账户已被锁定，请联系管理员");
        }
        //往info对象中添加用户信息,Token字符串
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user,token,getName());
        return info;
    }
}
